package com.example.close_order.repository;

import com.example.close_order.entity.Order;
import com.example.close_order.enums.OrderStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
    
    Optional<Order> findByOrderNo(String orderNo);
    
    List<Order> findByStatusAndExpireTimeBefore(OrderStatus status, LocalDateTime expireTime);
    
    @Query("SELECT o FROM Order o WHERE o.status IN :statuses AND o.expireTime < :now")
    List<Order> findExpiredOrders(@Param("statuses") List<OrderStatus> statuses, 
                                 @Param("now") LocalDateTime now);
    
    @Modifying
    @Query("UPDATE Order o SET o.status = 'CLOSED', o.closeTime = :closeTime, o.updateTime = :updateTime " +
           "WHERE o.id = :id AND o.status IN :statuses AND o.version = :version")
    int closeOrderWithVersion(@Param("id") Long id, 
                             @Param("statuses") List<OrderStatus> statuses,
                             @Param("closeTime") LocalDateTime closeTime,
                             @Param("updateTime") LocalDateTime updateTime,
                             @Param("version") Integer version);
}